<template>
  <a-modal
    v-model:open="open"
    v-model:title="title"
    @ok="handleOk"
    @cancel="handleCancle"
    width="488px"
  >
    <div>
      <a-form
        ref="formUserRef"
        :model="formUser"
        :rules="rules"
        :label-col="{ style: 'width:122px' }"
      >
        <a-form-item label="用户名" name="userName">
          <a-input
            v-model:value="formUser.userName"
            placeholder="请输入"
            style="width: 342px; height: 32px"
            :maxlength="32"
          />
        </a-form-item>
        <a-form-item label="职称" name="userTitle">
          <a-input
            v-model:value="formUser.userTitle"
            placeholder="请输入"
            style="width: 342px; height: 32px"
          />
        </a-form-item>
        <a-form-item label="工号" name="workNumber">
          <a-input
            v-model:value="formUser.workNumber"
            placeholder="请输入"
            style="width: 342px; height: 32px"
          />
        </a-form-item>
        <a-form-item label="所属部门" name="userDept">
          <a-input
            v-model:value="formUser.userDept"
            placeholder="请输入"
            style="width: 342px; height: 32px"
          />
        </a-form-item>
        <a-form-item label="入职日期" name="joinTime">
          <a-date-picker
            v-model:value="formUser.joinTime"
            :format="dateFormat"
            :value-format="dateFormat"
            type="date"
            placeholder="请选择"
            style="width: 342px; height: 32px"
            @change="handleChangeJoinTime"
          />
        </a-form-item>
        <a-form-item label="手机号" name="mobile">
          <a-input
            v-model:value="formUser.mobile"
            placeholder="请输入"
            style="width: 342px; height: 32px"
          />
        </a-form-item>
        <a-form-item label="工作状态" name="userStatus">
          <a-select
            v-model:value="formUser.userStatus"
            :options="userStatusOptions"
            placeholder="请选择"
            style="width: 342px; height: 32px"
            @change="handleSelectStatus"
          ></a-select>
        </a-form-item>
        <a-form-item
          label="实习截止日期"
          name="internshipEndDate"
          v-if="formUser.userStatus === 'intern'"
        >
          <a-date-picker
            v-model:value="formUser.internshipEndDate"
            :format="dateFormat"
            :value-format="dateFormat"
            :disabled-date="disabledDate"
            type="date"
            placeholder="请选择"
            style="width: 342px; height: 32px"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>
<script setup>
import { reactive, ref, watch } from 'vue'
import { useVModel } from '@vueuse/core'
import { checkUser } from '@/api/user.js'
import dayjs from 'dayjs'
const dateFormat = 'YYYY-MM-DD'
/**
 * 外部参数
 */
let props = defineProps({
  open: { type: Boolean, default: () => true },
  title: {
    type: String,
    default() {
      return ''
    },
  },
  contextData: { ype: Object, default: () => {} },
})
/**
 * 事件定义
 */
let emit = defineEmits(['update:open', 'update:title', 'edit', 'save'])
/**
 * 双向绑定
 */
let open = useVModel(props, 'open', emit)
let title = useVModel(props, 'title', emit)

const userStatusOptions = ref([
  {
    value: 'job',
    label: '在职',
  },
  {
    value: 'intern',
    label: '实习',
  },
  {
    value: 'resign',
    label: '离职',
  },
])
let formUserRef = ref()

let formUser = reactive({
  userName: undefined,
  userTitle: undefined,
  workNumber: undefined,
  userDept: undefined,
  joinTime: undefined,
  mobile: undefined,
  userStatus: 'job',
  internshipEndDate: undefined,
})
let rules = {
  userName: [
    {
      required: true,
      message: '此项为必填项',
      trigger: 'change',
    },
  ],
  workNumber: [
    {
      required: true,
      validator: checkUniqueWorkNumber,
      trigger: 'change',
    },
  ],
  joinTime: [
    {
      required: true,
      message: '此项为必填项',
      trigger: 'change',
    },
  ],
  mobile: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号',
      change: 'change',
    },
  ],
  internshipEndDate: [
    {
      validator: checkInternshipEndDate,
      trigger: 'change',
    },
  ],
}
//form表单数据变化
watch(
  () => props.contextData,
  contextData => {
    if (contextData.btnType === 'edit') {
      formUser = reactive({ ...formUser, ...contextData.data })
    }
  },
  { deep: true, immediate: true },
)
const disabledDate = current => {
  if (formUser.joinTime) {
    return current && current < dayjs(formUser.joinTime).endOf('day')
  }
}
function resetForm() {
  formUserRef.value.resetFields()
}
let handleOk = e => {
  if (open.value) {
    formUserRef.value
      .validate()
      .then(() => {
        open.value = false
        if (props.contextData.btnType === 'edit') {
          emit('edit', formUser)
        } else {
          emit('save', formUser)
        }
        resetForm()
      })
      .catch(() => {})
  }
}
let handleCancle = () => {
  open.value = false
  formUserRef.value.resetFields()
}

// 检查工号是否已经被占用
async function checkUniqueWorkNumber(rule, value) {
  if (!value) {
    return Promise.reject('此项为必填项')
  } else {
    if (formUser.userStatus === 'intern') {
      const internPattern = /^10\d{6}$/
      if (!internPattern.test(value)) {
        return Promise.reject('实习生工号是8位数字,前两位为10')
      }
    } else if (formUser.userStatus === 'job') {
      const jobPattern = /^\d{6}$/
      if (!jobPattern.test(value)) {
        return Promise.reject('在职员工工号是6位数字')
      }
    } else if (formUser.userStatus === 'resign') {
      const resignedPattern = /^(?:\d{6}|10\d{6})$/
      if (!resignedPattern.test(value)) {
        return Promise.reject(
          '离职员工的工号必须是6位数字或8位数字且前两位为10',
        )
      }
    }
    let params = {
      workNumber: value,
      userId: formUser.userId,
    }
    let result = await checkUser(params)
    if (!result.data) {
      return Promise.reject('此此工号已重复')
    } else {
      return Promise.resolve()
    }
  }
}
// 检查实习截止日期是否早于入职日期
function checkInternshipEndDate(_, value) {
  if (!value) {
    return Promise.resolve()
  }
  const joinDate = formUser.joinTime
  if (joinDate && dayjs(value).isBefore(dayjs(joinDate), 'day')) {
    return Promise.reject('实习截止日期不能早于入职日期')
  }
  return Promise.resolve()
}
// 工作状态变化时，触发工号校验
function handleSelectStatus() {
  formUserRef.value.validateFields(['workNumber'])
}
// 入职日期变化时，触发实习日期校验
function handleChangeJoinTime() {
  formUserRef.value.validateFields(['internshipEndDate'])
}
</script>
<style lang="less" scoped>
:global(.ant-modal .ant-modal-content) {
  padding: 16px 0px 10px 0px;
  background: #fff;
  border-radius: 2px;
  box-shadow:
    0 6px 16px 0 rgba(0, 0, 0, 0.08),
    0 9px 4px 0 rgba(0, 0, 0, 0.05),
    0 12px 48px 16px rgba(0, 0, 0, 0.03);
}
:global(.ant-modal .ant-modal-footer) {
  padding-right: 24px;
  padding-top: 10px;
  border-top: 1px solid rgba(0, 0, 0, 0.09);
}
:global(.ant-modal .ant-modal-header .ant-modal-title) {
  line-height: 24px;
  font-weight: 500;
  font-family: PingFangSC-Medium;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 16px;
}
:global(.ant-modal .ant-modal-header) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.09);
  padding-left: 24px;
}
:global(.ant-form-item .ant-form-item-label) {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.85);
  line-height: 22px;
  text-align: right;
  font-family: PingFangSC-Regular;
}
</style>
